package com.sunday.android.fangdaifu.bukong.fragment.tab;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.sunday.android.fangdaifu.bukong.BaseApp;
import com.sunday.android.fangdaifu.bukong.MainActivity;
import com.sunday.android.fangdaifu.bukong.R;
import com.sunday.android.fangdaifu.bukong.activity.index.ProjectListActivity;
import com.sunday.android.fangdaifu.bukong.adapter.BaoListAdapter;
import com.sunday.android.fangdaifu.bukong.adapter.SpinnerAdapter;
import com.sunday.android.fangdaifu.bukong.entity.ProjectListItem;
import com.sunday.android.fangdaifu.bukong.entity.WarnItem;
import com.sunday.android.fangdaifu.bukong.entity.event.SelectProject;
import com.sunday.android.fangdaifu.bukong.http.ApiClient;
import com.sunday.android.fangdaifu.bukong.utils.BaseUtil;
import com.sunday.android.fangdaifu.bukong.utils.Constants;
import com.sunday.android.fangdaifu.bukong.utils.LazyFragment;
import com.sunday.common.event.EventBus;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.member.base.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/29.
 */

public class BaoFragment extends LazyFragment implements View.OnClickListener {

    @Bind({R.id.tvName01, R.id.tvName02, R.id.tvName03})
    List<TextView> nameList;
    @Bind({R.id.tab01, R.id.tab02, R.id.tab03})
    List<LinearLayout> layoutList;
    @Bind(R.id.left_btn)
    ImageView leftBtn;
    @Bind(R.id.etSearch)
    EditText etSearch;
    @Bind(R.id.imgSearch)
    ImageView imgSearch;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.emptylayout)
    EmptyLayout emptylayout;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;
    @Bind(R.id.tvTypeShow)
    TextView tvTypeShow;
    private PopupWindow popupWindow;

    private LinearLayoutManager layoutManager;
    private BaoListAdapter adapter;
    private List<WarnItem> warnList = new ArrayList<>();

    private String searchContent;//搜索内容 === plantNo
    private Integer type = null,status = null;
    private Long projectId = null;
    private long memberId;
    private boolean isPrepared;
    private boolean mHasLoadedOnce;
    private String[] spinnerStr;

    public static BaoFragment newInstance() {
        BaoFragment fragment = new BaoFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_bao, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        memberId = BaseApp.getInstance().getMemberId();
        initView();
        isPrepared = true;
        lazyLoad();
        handleRecycle();
    }

    private void initView() {
        showType(false,null);
        spinnerStr = getResources().getStringArray(R.array.type);
        refreshLayout.setColorSchemeResources(R.color.material_red, R.color.material_green,
                R.color.material_blue, R.color.material_yellow);
        layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new BaoListAdapter(mContext,warnList);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext).color(Color.parseColor("#999999")).build());
        etSearch.setOnKeyListener(onKeyListener);
        initTypeList();
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        mHasLoadedOnce = true;
        getData();
    }

    @OnClick({R.id.tab01, R.id.tab02 ,R.id.tab03,R.id.left_btn, R.id.imgSearch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tab01:
                intent = new Intent(mContext,ProjectListActivity.class);
                startActivityForResult(intent, Constants.SELECT_PROJECT_ITEM);
//                setSelectItem(0);
//                nameList.get(2).setSelected(false);
//                nameList.get(2).setText("类型");
//                showType(false,null);
//                searchContent=null;
//                etSearch.setText("");
//                status = null;
//                projectId = null;
//                type = null;
//                getData();
                break;
            case R.id.tab02:
                nameList.get(1).setSelected(!nameList.get(1).isSelected());
                status = nameList.get(1).isSelected()?1:0;
                getData();
                break;
            case R.id.tab03:
                popupWindow.update();
                popupWindow.showAsDropDown(layoutList.get(2),0,20);
                break;
            case R.id.left_btn://返回首页
                MainActivity mainActivity = (MainActivity)getActivity();
                mainActivity.setViewPagerIndex(0);
                break;
            case R.id.imgSearch://搜索
                searchContent = etSearch.getText().toString().trim();
                getData();
                break;
        }
    }

    private void initTypeList(){
        popupWindow = new PopupWindow(mContext);
        popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        View view = LayoutInflater.from(mContext).inflate(R.layout.popu_layout, null);
        ButterKnife.findById(view,R.id.tv1).setOnClickListener(this);
        ButterKnife.findById(view,R.id.tv2).setOnClickListener(this);
        ButterKnife.findById(view,R.id.tv3).setOnClickListener(this);
        popupWindow.setContentView(view);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
    }

    private void loading(){
        if (!refreshLayout.isRefreshing()){
            refreshLayout.setRefreshing(true);
        }
    }

    private void getData(){
        loading();
        Call<ResultDO<List<WarnItem>>> call = ApiClient.getApiAdapter().BaWarningList(memberId,searchContent,projectId,type,status,pageNo,pageSize);
        call.enqueue(new Callback<ResultDO<List<WarnItem>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<WarnItem>>> call, Response<ResultDO<List<WarnItem>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    warnList.clear();
                    warnList.addAll(response.body().getResult());
                    if (warnList.isEmpty()){
                        emptylayout.setErrorType(EmptyLayout.NODATA);
                        emptylayout.setErrorMessage("暂无数据");
                    }else {
                        emptylayout.setVisibility(View.GONE);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<WarnItem>>> call, Throwable t) {
                if (isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
            }
        });
    }

    private int pageNo = 1, pageSize = 10;
    private boolean isCanloadMore = false;
    private int lastVisibleItem;

    private void handleRecycle() {
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                getData();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&
                        lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    pageNo++;
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                isCanloadMore = dy > 0;
            }
        });
    }


    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){
                searchContent = etSearch.getText().toString().trim();
                getData();
                return true;
            }
            return false;
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode== Constants.SELECT_PROJECT_ITEM_RESULT){
            Bundle bundle = data.getBundleExtra("bean");
            ProjectListItem.ListBean selectProject = (ProjectListItem.ListBean) bundle.getSerializable("bean");
            projectId = selectProject.getId();
            nameList.get(0).setText(selectProject.getName());
            getData();
        }
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    private void showType(boolean isShow,String str){
        if (isShow){
            tvTypeShow.setVisibility(View.VISIBLE);
            tvTypeShow.setText(str);
        }else {
            tvTypeShow.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        type = Integer.parseInt(String.valueOf(v.getTag()));
        nameList.get(2).setSelected(true);
        nameList.get(2).setText(spinnerStr[type-1]);
        showType(true,spinnerStr[type-1]);
        popupWindow.dismiss();
        getData();
    }
}
